import React, {useEffect, useState} from 'react';
import {Modal, Button, Radio, Col, Row, Form, Input, Select, message} from 'antd';
import './index.less';
import SqlEdit from './SqlEdit';
import {Space} from 'antd';
import {MinusCircleOutlined, PlusOutlined, PlusCircleOutlined} from '@ant-design/icons';
import DataTablePanels from "@/pages/components/DataTablePanels";
import axios from "axios";

export default function AddApi(props) {
  const {addModalVisible, setAddModalVisible, getAllApiConfigInfo, apiManage: {}, dispatch, prefix} = props;
  const [isBasic, setIsBasic] = useState(true);
  const [value, setValue] = React.useState(1);
  const [groupData, setGroupData] = useState([]);
  const [dataSourceData, setDataSourceData] = useState([]);
  const [dataTable, setDataTable] = useState([]);
  const [sqlText, setSqlText] = useState('');
  const [basicForm] = Form.useForm();
  const [proForm] = Form.useForm();

  const handleOk = () => {
    // setAddModalVisible(false);
    const basic = basicForm.getFieldsValue();
    const pro = proForm.getFieldsValue();
    console.log("basic", basic);
    console.log("pro", pro);
    let d = {...basic, ...pro, sqlList: [{sqlText: sqlText}], previlege: value};
    d.params = JSON.stringify(d.params);
    console.log("提交", d);
    const path = "http://127.0.0.1:8520/apiConfig/add";
    const buildPath = "http://121.4.195.203/server/apiConfig/add"
    axios.post( buildPath, d, {
      headers: {
        'Content-Type': 'application/json',
        "Authorization": sessionStorage.getItem("token") //'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNjQ3MTQ2MjIxLCJpYXQiOjE2NDQ3MjcwMjF9.OajOZaSMi674di_dx1u5r86AcliW0y7GMApMbWdP4W4'
      }
    }).then(res => {
      getAllApiConfigInfo();
      setAddModalVisible(false);
    });
  };

  const handleCancel = () => {
    setAddModalVisible(false);
  };

  const handleClickBasic = () => {
    setIsBasic(true);
  };

  const handleClickAdvanced = () => {
    setIsBasic(false);
    // dispatch({
    //   type:"pluginManage/getPlugins"
    // }).then(res => {
    //   if (res.success) {
    //     let data = res.data;
    //
    //   }
    // })
  };

  const onFinish = values => {
    console.log('Success:', values);
    console.log("basicForm", basicForm);

  };

  const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);
  };

  const {Option} = Select;

  function onChange(value) {
    console.log(`selected ${value}`);
    dispatch({
      type: "tableManage/getAllTables",
      payload: {
        sourceId: value
      }
    }).then(res => {
      setDataTable(res);
    });
  }

  const onRadioChange = e => {
    console.log('radio checked', e.target.value);
    setValue(e.target.value);
  };

  function onSearch(val) {
    console.log('search:', val);
  }

  function getGroupOptionsFromServer() {
    dispatch({
      type: "apiManage/getGroups"
    }).then(res => {
      let ops = Array();
      res.forEach(t => ops.push({label: t.name, value: t.id}));
      setGroupData(ops);
    });
  }

  function getGroupOptions() {
    return groupData.map((item, index) => {
      return (<Option value={item.value}>{item.label}</Option>)
    });
  }

  function getDataSourceFromServer() {
    dispatch({
      type: "dataSource/getAllDataSource"
    }).then(res => {
      let d = Array();
      res.forEach(t => d.push({id: t.id, name: t.name}));
      setDataSourceData(d);
    });
  }

  function getDataSourceOptions() {
    return dataSourceData.map((item, index) => {
      return (<Option value={item.id}>{item.name}</Option>)
    });
  }

  function getSqlText(sql) {
    setSqlText(sql);
  }

  return (
    <Modal
      className="add-api"
      okText="确认"
      cancelText="取消"
      footer={[
        <Button key="back" onClick={handleCancel}>
          取消
        </Button>,
        <Button
          key="submit"
          type="primary"
          htmlType="submit"
          onClick={handleOk}>
          确定
        </Button>,
      ]}
      visible={addModalVisible}
      onOk={handleOk}
      onCancel={handleCancel}
      width="900px"
    >
      <div className="title">新增API</div>
      <div className="menu">
        <Button
          onClick={handleClickBasic}
          style={{
            backgroundColor: !isBasic ? '#ffffff' : '#1890ff',
            color: isBasic ? '#ffffff' : '#1890ff',
          }}
        >
          基础配置
        </Button>
        <Button
          onClick={handleClickAdvanced}
          style={{
            backgroundColor: isBasic ? '#ffffff' : '#1890ff',
            color: !isBasic ? '#ffffff' : '#1890ff',
          }}
        >
          高级配置
        </Button>
      </div>

      {/*{isBasic && (*/}
      <Form
        name="basic"
        form={basicForm}
        labelCol={{span: 8}}
        wrapperCol={{span: 16}}
        initialValues={{remember: true}}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        hidden={!isBasic}
      >
        <div className="basic-msg">
          <div className="title-font">基础信息</div>
          <Row gutter={16} className="form-item">
            <Col span={8}>
              <Form.Item
                label="API名称"
                name="name"
                rules={[{required: true, message: '请输入API名称'}]}
              >
                <Input/>
              </Form.Item>
            </Col>
            <Col span={16}>
              <Form.Item
                label="请求地址"
                name="path"
                labelCol={{span: 5}}
                wrapperCol={{span: 19}}
                rules={[{required: true, message: '请输入API对应的请求地址'}]}
              >
                {/*<span className="prefix">http://127.0.0.1.8520/api/</span>*/}
                <Input addonBefore={<span>http://127.0.0.1:8520/api/</span>}/>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="API分组"
                name="groupId"
                rules={[{required: true, message: '请选择API分组'}]}
              >
                <Select
                  style={{borderRadius: '0px'}}
                  showSearch
                  placeholder="选择分组"
                  optionFilterProp="children"
                  onChange={getGroupOptionsFromServer}
                  onSearch={onSearch}
                  onClick={getGroupOptionsFromServer}
                >
                  {getGroupOptions()}
                  {/*<Option value="jack">Jack</Option>*/}
                  {/*<Option value="lucy">Lucy</Option>*/}
                  {/*<Option value="tom">Tom</Option>*/}
                </Select>
              </Form.Item>
            </Col>
            <Col span={16}>
              <Form.Item
                label="描述(note)"
                className="describe"
                name="note"
                labelCol={{span: 5}}
                wrapperCol={{span: 19}}
                rules={[{required: true, message: '请输入'}]}
              >
                <Input/>
              </Form.Item>
            </Col>
          </Row>
        </div>
        <div className="sql">
          <div className="title-font">SQL配置</div>
          <Row>
            <Col span={8}>
              <Form.Item
                label="数据源"
                name="datasourceId"
                rules={[{required: true, message: '请输入'}]}
              >
                <Select
                  style={{borderRadius: '0px'}}
                  showSearch
                  placeholder="Select a person"
                  optionFilterProp="children"
                  onClick={getDataSourceFromServer}
                  onChange={onChange}
                  onSearch={onSearch}
                >
                  {getDataSourceOptions()}
                  {/*<Option value="jack">Jack</Option>*/}
                  {/*<Option value="lucy">Lucy</Option>*/}
                  {/*<Option value="tom">Tom</Option>*/}
                </Select>
              </Form.Item>
              <Button type="primary" style={{width: '100%', marginBottom: '10px'}}>
                数据表
              </Button>
              {/*<div style={{overflow: 'scroll', height: '160px', overflowX: 'hidden'}}>*/}
              {/*  createTablePanels();*/}
              {/*  <TablePanel tableName="table_1" list={[11, 'name', 'age', 'school']}/>*/}
              {/*  <TablePanel tableName="table_2" list={[11, 'name', 'age', 'school']}/>*/}
              {/*  <TablePanel tableName="table_3" list={[11, 'name', 'age', 'school']}/>*/}
              {/*  <TablePanel tableName="table_4" list={[11, 'name', 'age', 'school']}/>*/}
              {/*  <TablePanel tableName="table_4" list={[11, 'name', 'age', 'school']}/>*/}
              {/*  <TablePanel tableName="table_4" list={[11, 'name', 'age', 'school']}/>*/}
              {/*  <TablePanel tableName="table_4" list={[11, 'name', 'age', 'school']}/>*/}
              {/*  <TablePanel tableName="table_4" list={[11, 'name', 'age', 'school']}/>*/}
              {/*</div>*/}
              <DataTablePanels data={dataTable}/>
            </Col>
            <Col span={16}>
              <SqlEdit onChange={getSqlText}/>
            </Col>
          </Row>
        </div>
        <div className="param">
          <div className="title-font">参数配置</div>

          <Form.List name="params">
            {(fields, {add, remove}) => (
              <>
                {fields.map(({key, name, ...restField}) => (
                  <>
                    <Space
                      key={key}
                      style={{display: 'flex', marginBottom: 8}}
                      align="baseline"
                    >
                      <Row gutter={16}>
                        <Col span={7}>
                          <Form.Item
                            {...restField}
                            label="参数名称"
                            name={[name, 'name']}
                            labelCol={{span: 9}}
                            wrapperCol={{span: 15}}
                            rules={[{required: true, message: '请输入参数名称'}]}
                          >
                            <Input placeholder="请输入参数名称"/>
                          </Form.Item>
                        </Col>
                        <Col span={7}>
                          <Form.Item
                            {...restField}
                            label="参数类型"
                            name={[name, 'type']}
                            labelCol={{span: 9}}
                            wrapperCol={{span: 15}}
                            rules={[{required: true, message: '请选择参数类型'}]}
                          >
                            <Select
                              showSearch
                              placeholder="选择参数类型"
                              optionFilterProp="children"
                              // onChange={onChange}
                              onSearch={onSearch}
                              filterOption={(input, option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                              }
                            >
                              <Option value="string">string</Option>
                              <Option value="bigint">bigint</Option>
                              <Option value="double">double</Option>
                              <Option value="date">date</Option>
                              <Option value="Array<string>">string 数组</Option>
                              <Option value="Array<bigint>">bigint 数组</Option>
                              <Option value="Array<double>">double 数组</Option>
                              <Option value="Array<date>">date 数组</Option>
                            </Select>
                          </Form.Item>
                        </Col>
                        <Col span={10}>
                          <Form.Item
                            {...restField}
                            label="参数说明"
                            name={[name, 'note']}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 16}}
                            rules={[{required: false, message: '请输入参数说明'}]}
                          >
                            <Input/>
                          </Form.Item>
                        </Col>
                      </Row>
                      <MinusCircleOutlined onClick={() => remove(name)}/>
                    </Space>
                  </>
                ))}
                <Form.Item>
                  <PlusCircleOutlined onClick={() => add()}/>
                </Form.Item>
              </>
            )}
          </Form.List>
        </div>

        <div className="privilege">
          <div className="title-font">权限配置</div>
          <Radio.Group onChange={onRadioChange} value={value}>
            <Radio value={0}>私有</Radio>
            <Radio value={1}>开放</Radio>
          </Radio.Group>
        </div>

        {/*<Form.Item*/}
        {/*  wrapperCol={{*/}
        {/*    offset: 18,*/}
        {/*    span: 6,*/}
        {/*  }}*/}
        {/*>*/}
        {/*  <Button style={{marginRight: '10px', marginTop: '10px'}} onClick={handleCancel}>取消</Button>*/}
        {/*  <Button type="primary" htmlType="submit">*/}
        {/*    确认*/}
        {/*  </Button>*/}
        {/*</Form.Item>*/}
      </Form>
      {/*)}*/}

      {/*{!isBasic && (*/}
      <div>
        <Form
          name="pro"
          form={proForm}
          labelCol={{span: 8}}
          wrapperCol={{span: 16}}
          initialValues={{remember: true}}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          hidden={isBasic}
        >
          <div className="title-font">数据转换</div>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="数据转换插件主类全类名"
                name="transformPlugin"
                rules={[{required: false, message: '请输入'}]}
              >
                <Input/>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="数据转换插件参数"
                name="transformPluginParams"
                rules={[{required: false, message: '请输入'}]}
              >
                <Input/>
              </Form.Item>
            </Col>
          </Row>
          <div className="title-font" style={{marginTop: '-20px'}}>
            缓存
          </div>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="缓存插件主类全类名"
                name="cachePlugin"
                rules={[{required: false, message: '请输入'}]}
              >
                <Input/>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="缓存插件参数"
                name="cachePluginParams"
                rules={[{required: false, message: '请输入'}]}
              >
                <Input/>
              </Form.Item>
            </Col>
          </Row>
          {/*<Form.Item*/}
          {/*  wrapperCol={{*/}
          {/*    offset: 18,*/}
          {/*    span: 6,*/}
          {/*  }}*/}
          {/*>*/}
          {/*  <Button style={{marginRight: '10px', marginTop: '10px'}}>取消</Button>*/}
          {/*  <Button type="primary" htmlType="submit">*/}
          {/*    确认*/}
          {/*  </Button>*/}
          {/*</Form.Item>*/}
        </Form>
      </div>
      {/*)}*/}
    </Modal>
  );
}
